﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DAO;
using DTO;
using System.Web.Routing;
using PTExpress.Models;

namespace PTExpress.Controllers
{
    [Authorize]
    public class QLChuyenXeController : Controller
    {
        protected  void Initialize()
        {

            XeDAO xeDao = new XeDAO();
            List<XeDTO> lsXe = xeDao.GetAllWhere("daxoa = 0");
            List<SelectListItem> lsXeItem = new List<SelectListItem>();
            lsXeItem.Add(new SelectListItem());
            foreach (XeDTO xe in lsXe)
            {
                SelectListItem item = new SelectListItem();
                item.Text = xe.TenXe;
                item.Value = xe.Id.ToString();
                lsXeItem.Add(item);
            }
            ViewData["lsEXe"] = lsXeItem;

            TuyenDuongDAO tuyenDuongDAO = new TuyenDuongDAO();
            List<TuyenDuongDTO> lsTuyenDuong = tuyenDuongDAO.GetAll();
            List<SelectListItem> lsTuyenDuongItem = new List<SelectListItem>();
            lsTuyenDuongItem.Add(new SelectListItem());
            foreach (TuyenDuongDTO xe in lsTuyenDuong)
            {
                SelectListItem item = new SelectListItem();
                item.Text = string.Format("{0} đi {1}", xe.NoiDi, xe.NoiDen);
                item.Value = xe.Id.ToString();
                lsTuyenDuongItem.Add(item);
            }
            ViewData["lsETuyenDuong"] = lsTuyenDuongItem;
        }

        public ActionResult Index()
        {
            ChuyenXeDAO xeDAO = new ChuyenXeDAO();
            List<ChuyenXeDTO> ls = xeDAO.GetAll();
            this.ViewData.Add("dsChuyenXe", ls);
            return View();
        }

        public ActionResult Them()
        {
            Initialize();
            ChuyenXe model = new ChuyenXe();
            model.XuatPhat = DateTime.Now;
            model.DenNoi = DateTime.Now;
            return View(model);
        }

        [HttpPost]
        public ActionResult Them(ChuyenXe model)
        {
            ViewData["IsValid"] = ModelState.IsValid;
            if (ModelState.IsValid)
            {
                ChuyenXeDTO chuyenXeDTO = new ChuyenXeDTO();
                ChuyenXeDAO chuyenXeDAO = new ChuyenXeDAO();
                chuyenXeDTO.DenNoi = model.DenNoi;
                chuyenXeDTO.GiaVe = model.giaVe;
                chuyenXeDTO.TuyenDuongId = model.TuyenDuong;
                chuyenXeDTO.XeId = model.Xe;
                chuyenXeDTO.XuatPhat = model.XuatPhat;
                bool thanhCong = chuyenXeDAO.AddNew(chuyenXeDTO);
                ViewData["ThanhCong"] = thanhCong;
                if (thanhCong)
                {
                    return RedirectToAction("Index", "QLChuyenXe");
                }
            }

            Initialize();
            return View(model);
        }

    }
}
